import React, { Component } from 'react';
import {bindActionCreators} from 'redux'
import { connect} from 'react-redux'
import * as actions from '../actions/actions.js'

import ListView from '../components/ListView';
import BottomBar from '../components/BottomBar';
import Banner from '../components/Banner';
import SlideNavigation from '../components/SlideNavigation';
import MessageAlert from '../components/MessageAlert'
import browserHistory from 'react-router/lib/browserHistory'
import {fetchGet,fetchPost} from '../utils/httpRequest'
import cookie from 'react-cookie'

class GiftContainer extends Component {


    constructor(props) {
        super(props);
        this.state = {
            cardData:{},
            cardCount: 1,
            showMessage:false,
            returnObj: {},
        };
        this._onScrollHandle = this.onScrollHandle.bind(this);
    }

    componentWillReceiveProps(nextProps){
        //console.log("nextProps",nextProps.location.query,"session",sessionStorage.getItem("payFront"));
        if(nextProps.location.query.returnStatus==1){
            //如果sessionStorage有 不调用
            if(sessionStorage.getItem("payFront")!=null&&sessionStorage.getItem("payFront")==nextProps.location.query.orderno){
            }else{
                sessionStorage.setItem("payFront",nextProps.location.query.orderno);
                this.props.frontPayBack(nextProps.location.query.orderno,1);
            }
        }
    }

    pay( type) {
        sessionStorage.removeItem("payFront");
        try{
            var uid=cookie.load('mobile');
            if(!uid||uid=="undefined"){
                window.sessionStorage.setItem("retUrl","/gifts");
                //alert('登录失效');
                browserHistory.replace({
                    pathname: '/login'
                });
                return ;
            }

            if(this.state.returnObj&&this.state.returnObj==0) {//存在取到数据未完成跳转是再发请求的情况
                return ;
            }


            if (type ==1 ){
                //微信支付
                if (null!=this.state.returnObj.code&&this.state.returnObj.code == 0){
                    try{
                        //获取微信支付地址成功
                        window.location.href = this.state.returnObj.data;
                    }catch(e2){
                        alert('微信支付error4',e2)
                    }
                }else {

                    let para = {uid:uid, card_id:this.state.cardData.card_id, card_number:1,wx_pay:1,o2osign:cookie.load("o2osign"),act_id:666};
                    $('#loadingToast').show();
                    fetchPost('pay', para)
                        .then(response => response.json())
                        .then(json => {
                            $('#loadingToast').hide();
                            this.state.returnObj = json;
                            try{
                                if (this.state.returnObj.code == 0) {
                                    //获取订单信息成功
                                    window.location.href = this.state.returnObj.data;
                                }else{
                                    this.setState({returnObj: json,showMessage:true});
                                }
                            }catch(e2){
                                alert('微信支付error2',e2)
                            }
                        })
                }
            }else {
                //支付平台支付
                if (null!=this.state.returnObj.code&&this.state.returnObj.code == 0){
                    try{
                        //获取订单信息成功
                        var form1 = document.getElementById("myform");
                        form1 .submit();
                    }catch(e2){
                        alert('error4',e2)
                    }
                }else {
                    let para = {uid:uid, card_id:this.state.cardData.card_id, card_number:1,wx_pay:0,o2osign:cookie.load("o2osign"),act_id:666};

                    $('#loadingToast').show();
                    fetchPost('pay', para)
                        .then(response => response.json())
                        .then(json => {

                            $('#loadingToast').hide();
                            this.state.returnObj = json;
                            try{
                                //console.log(this.state.returnObj)
                                if (this.state.returnObj.code == 0) {
                                    //获取订单信息成功
                                    var form1 = document.getElementById("myform");
                                    $("#reqseq").val(json.data.reqseq);
                                    $("#signLicense").val(json.data.signLicense);
                                    $("#apptype").val(json.data.apptype);
                                    $("#smkUserId").val(json.data.smkUserId);
                                    $("#FrontUrl").val(json.data.FrontUrl);
                                    $("#txntype").val(json.data.txntype);

                                    if(window.sessionStorage.getItem("openid")){
                                        $("#openid").val(window.sessionStorage.getItem("openid"));
                                    }else{
                                        $("#openid").val("");
                                    }

                                    form1.submit();

                                }else{
                                    this.setState({returnObj: json,showMessage:true});
                                }
                            }catch(e2){
                                alert('error2',e2)
                            }
                        })
                }
            }
        }catch(e){
            alert(e);
        }



    }


    componentWillUnmount(){
        window.removeEventListener("scroll", this._onScrollHandle);
    }

    onScrollHandle(event){
        //console.log(this.getScrollTop(),this.getWindowHeight(),this.getScrollHeight());
        if(this.getScrollTop() + this.getWindowHeight() == this.getScrollHeight()){
            if (this.props.needFetch) {
                let page = this.props.currentPage + 1;
                this.props.vauleCardListFetch(page,666);
            }
        }
        //if($("#SlideNavi").hasClass("header_fixed")){//已固定
        //    console.log($(".bottomBar").offset().top,"fixed");
        //    if($(".bottomBar").offset().top<535){
        //        $("#SlideNavi").removeClass("header_fixed");
        //    }else{
        //
        //    }
        //}else{//未固定
        //    if($(".bottomBar").offset().top>556) {
        //        $("#SlideNavi").addClass("header_fixed");
        //    }
        //    console.log($(".bottomBar").offset().top,"no fix");
        //
        //}
        //底部距离顶部的距离>窗口高度
        if($(".bottomBar").offset().top>$(window).height()+75){
            //console.log(this.getScrollTop());
            //console.log($("#SlideNavi").offset().top)
            //固定到顶部后 top 变为0
            //console.log("大");
            if(!$("#SlideNavi").hasClass("header_fixed")){
                $(".cardContainer").css("padding-top","120px");
                $("#SlideNavi").addClass("header_fixed");

            }
            //console.log(1);
        }else{
            //console.log(2);
            if($("#SlideNavi").hasClass("header_fixed")){
                $(".cardContainer").css("padding-top","0px");
                $("#SlideNavi").removeClass("header_fixed");
            }

        }

    }



    getScrollTop(){
        //var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
        //if(document.body){
        //    bodyScrollTop = document.body.scrollTop;
        //}
        //if(document.documentElement){
        //    documentScrollTop = document.documentElement.scrollTop;
        //}
        //scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
        // console.log($();
        return $(document).scrollTop();
    }

//文档的总高度

    getScrollHeight(){
        var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
        if(document.body){
            bodyScrollHeight = document.body.scrollHeight;
        }
        if(document.documentElement){
            documentScrollHeight = document.documentElement.scrollHeight;
        }
        scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
        return scrollHeight;
    }

//浏览器视口的高度

    getWindowHeight(){
        var windowHeight = 0;
        if(document.compatMode == "CSS1Compat"){
            windowHeight = document.documentElement.clientHeight;
        }else{
            windowHeight = document.body.clientHeight;
        }
        return windowHeight;
    }


    componentWillMount() {
        window.addEventListener("scroll", this._onScrollHandle);
        window.sessionStorage.setItem("retUrl","/gifts");
        //第一次进入会携带 手机号和user_id为用户做自动登录
        //之后刷新页面和再次进入将不会有user_id

        //购买使用mobile & o2osign
        //自动登录使用第一次的mobile&user_id
        document.title="市民卡新人大礼包";
        history.pushState({}, "市民卡新人大礼包", "gifts");
        //console.log(this.props.location.query);
        var username=this.props.location.query.username;
        //var user_id=this.props.location.query.user_id;

        var department_id=666;
        this.props.bannerListFetch(department_id);
        this.props.vauleCardListFetch(1, department_id);

        if(username){
            //判断用户是否处于活动中 做自动登录
            $('#loadingToast').show();
            fetchPost('checkAct', {act_id:666,mobile:username})
            .then(
                    response => {
                        $('#loadingToast').hide();
                        return response.json()
                    }
            ).then(json => {
                    if(json.code==0){
                        cookie.save('mobile',username,{path:'/',maxAge:3*24*3600});
                        cookie.save('smid',json.data.smid,{path:'/',maxAge:3*24*3600});
                        cookie.save('o2osign',json.data.o2osign,{path:'/',maxAge:3*24*3600});
                    }

                //console.log(json);
            })
        }
        //判断是否已登录过
        if(!username&&!cookie.load('mobile')){
            //alert("自动登录失败");
        }

    }

    setBuyCard(cardData){
        //console.log(cardData);
        this.setState({cardData:cardData});
    }
    hanlde(type) {
        var that = this;
        return function () {
            that.setState({showMessage: false})
        }

    }
    render() {

        return (
            <div>
                {<Banner data={this.props.bannerlist.data} />}
                {<SlideNavigation cates={this.props.bannerlist.cates} />}
                <div className="cardContainer" style={{ margin:"10px 20px 80px 20px",paddingBottom:"40px"}}>
                    {<ListView  dataList={this.props.valueCardList} clickFunc={this.setBuyCard.bind(this)} itemType={-1}/>}
                </div>
                <BottomBar/>


                <div id="actionSheet_wrap">
                    <div className="weui_mask_transition" id="mask"></div>
                    <div className="weui_actionsheet" id="weui_actionsheet">
                        <div className="weui_actionsheet_menu">
                            <div className="weui_actionsheet_cell" onClick={this.pay.bind(this,1)}>微信支付</div>
                            <div className="weui_actionsheet_cell" onClick={this.pay.bind(this,0)}>市民卡支付</div>
                        </div>
                        <div className="weui_actionsheet_action">
                            <div className="weui_actionsheet_cell" id="actionsheet_cancel">取消</div>
                        </div>
                    </div>
                </div>


                <form id="myform" name="myform" action="http://pay.96225.com/b2c_wap/c.action" method="post">
                    <input type="hidden" value="" name="reqseq" id="reqseq"/>
                    <input type="hidden" value="" name="signLicense" id="signLicense"/>
                    <input type="hidden" value="" name="apptype" id="apptype"/>
                    <input type="hidden" value="" name="smkUserId" id="smkUserId"/>
                    <input type="hidden" value="" name="FrontUrl" id="FrontUrl"/>
                    <input type="hidden" value="" name="txntype" id="txntype"/>
                    <input type="hidden" value="0" name="openid"  id="openid"/>
                </form>

                {this.state.showMessage&&
                <MessageAlert message={this.state.returnObj.msg} type={this.state.returnObj.code}
                              handle={this.hanlde.bind(this)}/>}
            </div>
        )
    }
}



function mapStateToProps(state) {

    var isNeedFetch = state.get('valueCardList').toJS().isNeedFetch;
    if (state.get('valueCardList').get('data').size<10){
        isNeedFetch =false
    }

    return {
        bannerlist : state.get('bannerlist').toJS(),
        //valueCardList : state.get('valueCardList').toJS().data,
        valueCardList : state.get('valueCardList'),
        currentPage:state.get('valueCardList').toJS().page,
        needFetch:isNeedFetch
    }
}
function mapDispatchToProps(dispatch) {

    return bindActionCreators(actions, dispatch);
}
GiftContainer.defaultProps = {

}


GiftContainer.propTypes = {}
module.exports=connect(mapStateToProps, mapDispatchToProps)(GiftContainer);


